import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/pages/models/notice_message_model.dart';
import 'package:inmotion_pro/service/global_service.dart';

// WebSocket消息模型
class WebSocketService extends GetxService with WidgetsBindingObserver {
  static WebSocketService get to => Get.find();

  // WebSocket连接实例
  WebSocket? _webSocket;

  // 消息流控制器 - 使用广播模式避免多个监听器时的异常
  late final StreamController<String> _messageController;

  // 连接状态流控制器
  late final StreamController<bool> _connectionController;

  // 心跳定时器
  Timer? _heartbeatTimer;

  // 重连定时器
  Timer? _reconnectTimer;

  // 未读消息数量 - 使用Rx进行响应式管理
  final RxInt unreadCount = 0.obs;

  // 消息列表 - 响应式列表，自动更新UI
  final RxList<NoticeMessageModel> messageList = <NoticeMessageModel>[].obs;

  // 连接配置
  String? _url;
  int _reconnectAttempts = 0;
  final int _maxReconnectAttempts = 5;

  // 连接状态标志，避免重复连接
  bool _isConnecting = false;
  bool _isDisposed = false;

  // 最后收到消息的时间戳
  int _lastMessageTimestamp = 0;

  // 公开的消息流 - 供外部监听消息
  Stream<String> get messageStream => _messageController.stream;

  // 公开的连接状态流 - 供外部监听连接状态
  Stream<bool> get connectionStream => _connectionController.stream;

  // 当前连接状态
  bool get isConnected =>
      _webSocket != null && _webSocket!.readyState == WebSocket.open;

  // 构造函数 - 初始化流控制器
  WebSocketService() {
    _messageController = StreamController<String>.broadcast();
    _connectionController = StreamController<bool>.broadcast();
  }

  @override
  void onInit() {
    super.onInit();
    // 注册应用生命周期监听
    WidgetsBinding.instance.addObserver(this);
    debugPrint('🎯 WebSocketService初始化完成');
  }

  @override
  void onClose() {
    _isDisposed = true;
    // 清理资源
    _cleanupResources();
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (_isDisposed) return;

    debugPrint('📱 应用生命周期状态变化: $state');

    switch (state) {
      case AppLifecycleState.resumed:
        // 应用回到前台时尝试重连
        _handleAppResumed();
        break;
      case AppLifecycleState.paused:
        // 应用进入后台 - 保持连接但停止不必要操作
        _handleAppPaused();
        break;
      case AppLifecycleState.inactive:
        // 应用失去焦点
        debugPrint('应用失去焦点，保持WebSocket连接');
        break;
      case AppLifecycleState.detached:
        // 应用被销毁 - 断开连接
        debugPrint('应用被销毁，断开WebSocket连接');
        _safeDisconnect();
        break;
      default:
        break;
    }
  }

  /// 连接到WebSocket服务器
  /// [url] WebSocket服务器地址
  Future<void> connect(String url) async {
    if (_isDisposed) {
      debugPrint('❌ WebSocketService已销毁,无法连接');
      return;
    }

    if (_isConnecting) {
      debugPrint('⏳ WebSocket连接正在进行中,跳过重复连接');
      return;
    }

    if (isConnected) {
      debugPrint('✅ WebSocket已连接,无需重复连接');
      return;
    }

    _url = url;
    return _performConnect();
  }

  /// 执行实际的WebSocket连接操作
  Future<void> _performConnect() async {
    if (_isDisposed) return;

    _isConnecting = true;

    try {
      debugPrint('🚀 开始连接WebSocket: $_url');

      // 建立WebSocket连接
      _webSocket = await WebSocket.connect(_url!, headers: {
        'x-auth': GlobalService.to.cacheUserInfo.value.xAuth,
      }).timeout(const Duration(seconds: 10));

      // 重置重连计数
      _reconnectAttempts = 0;
      _isConnecting = false;
      _lastMessageTimestamp = DateTime.now().millisecondsSinceEpoch;

      debugPrint('✅ WebSocket连接成功');

      // 安全地通知连接状态变化
      _safeAddConnectionState(true);

      // 设置消息监听
      _setupMessageListener();

      // 启动心跳机制
      _startHeartbeat();
    } catch (e) {
      _isConnecting = false;
      debugPrint('❌ WebSocket连接失败: $e');
      _handleError(e);
    }
  }

  /// 设置消息监听器
  void _setupMessageListener() {
    if (_webSocket == null || _isDisposed) return;

    _webSocket!.listen(
      (data) {
        if (_isDisposed) return;

        _lastMessageTimestamp = DateTime.now().millisecondsSinceEpoch;
        debugPrint('📨 接收到WebSocket消息: $data');

        // 安全地广播消息到所有监听器
        _safeAddMessage(data);

        // 解析并处理消息
        _parseAndHandleMessage(data);
      },
      onError: (error) {
        if (_isDisposed) return;
        debugPrint('❌ WebSocket监听错误: $error');
        _handleError(error);
      },
      onDone: () {
        if (_isDisposed) return;
        debugPrint('🔌 WebSocket连接正常关闭');
        _handleDisconnection();
      },
      cancelOnError: true,
    );
  }

  /// 安全地添加消息到流
  void _safeAddMessage(String message) {
    if (!_isDisposed && !_messageController.isClosed) {
      try {
        _messageController.add(message);
      } catch (e) {
        debugPrint('❌ 添加消息到流失败: $e');
      }
    }
  }

  /// 安全地添加连接状态到流
  void _safeAddConnectionState(bool isConnected) {
    if (!_isDisposed && !_connectionController.isClosed) {
      try {
        _connectionController.add(isConnected);
      } catch (e) {
        debugPrint('❌ 添加连接状态到流失败: $e');
      }
    }
  }

  /// 解析并处理接收到的消息
  void _parseAndHandleMessage(String data) {
    try {
      final messageMap = jsonDecode(data) as Map<String, dynamic>;
      final message = WebSocketMessageResponse.fromJson(messageMap);

      // 处理不同类型的消息
      _handleMessageByType(message);
    } catch (e) {
      debugPrint('❌ 消息解析失败: $e, 原始数据: $data');
    }
  }

  /// 根据消息类型处理消息
  void _handleMessageByType(WebSocketMessageResponse message) {
    debugPrint('🔧 处理消息类型: ${message.type}');

    switch (message.type) {
      case 'unread_notifications':
        _handleUnreadNotifications(message);
        break;
      case 'new_notification':
        _handleNewNotification(message);
        break;
      case 'pong':
        _handlePongMessage();
        break;
      default:
        _handleUnknownMessage(message);
        break;
    }
  }

  /// 处理未读通知消息 - 优化性能版本
  void _handleUnreadNotifications(WebSocketMessageResponse message) {
    debugPrint('📬 处理未读通知，数量: ${message.data?.length ?? 0}');

    if (message.data != null && message.data!.isNotEmpty) {
      // 使用Map来去重，提高性能
      final existingMessages = <int, NoticeMessageModel>{};
      for (var msg in messageList) {
        existingMessages[msg.id] = msg;
      }

      final newMessages = <NoticeMessageModel>[];
      int addedCount = 0;

      for (var notification in message.data!) {
        _logNotificationDetails(notification, '未读通知');

        // 如果消息不存在于当前列表，则添加
        if (!existingMessages.containsKey(notification.id)) {
          newMessages.add(notification);
          addedCount++;
        }
      }

      // 批量更新消息列表
      if (newMessages.isNotEmpty) {
        messageList.addAll(newMessages);
        debugPrint('✅ 添加了 $addedCount 条新未读消息');
      }

      // 更新未读计数
      unreadCount.value = message.data!.length;
    }
  }

  /// 处理新通知消息
  void _handleNewNotification(WebSocketMessageResponse message) {
    debugPrint('🔔 处理新通知');

    if (message.data != null && message.data!.isNotEmpty) {
      final notification = message.data![0];
      _logNotificationDetails(notification, '新通知');

      // 检查是否已存在相同ID的消息
      final existingIndex =
          messageList.indexWhere((item) => item.id == notification.id);
      if (existingIndex == -1) {
        // 添加到消息列表开头
        messageList.insert(0, notification);
        // 更新未读计数
        unreadCount.value++;
        debugPrint('✅ 新通知添加成功');
      } else {
        debugPrint('⏭️  通知已存在，跳过添加');
      }
    }
  }

  /// 处理Pong响应
  void _handlePongMessage() {
    debugPrint('🏓 接收到心跳响应url: $_url, ');
    // 更新最后收到心跳的时间
    _lastMessageTimestamp = DateTime.now().millisecondsSinceEpoch;
  }

  /// 处理未知类型消息
  void _handleUnknownMessage(WebSocketMessageResponse message) {
    debugPrint('❓ 未知消息类型: ${message.type}');
    if (message.data != null) {
      debugPrint('   数据: ${json.encode(message.data)}');
    }
  }

  /// 记录通知详情（用于调试）
  void _logNotificationDetails(NoticeMessageModel notification, String type) {
    if (!kDebugMode) return; // 只在调试模式下输出

    debugPrint('   $type详情:');
    debugPrint('     ID: ${notification.id}');
    debugPrint('     类型: ${notification.type}');
    debugPrint('     标题: ${notification.title}');
    debugPrint(
        '     内容: ${notification.content.en} / ${notification.content.zh}');
    debugPrint('     创建时间: ${notification.createdAt}');

    if (notification.data.sn.isNotEmpty) {
      debugPrint(
          '     附加数据: ${notification.data.sn} - (${notification.data.eventType} - ${notification.data.eventData})');
    }
    debugPrint('---');
  }

  /// 标记通知为已读 - 优化版本
  void markAsRead(int notificationId) {
    if (_isDisposed) return;

    if (isConnected) {
      sendJsonMessage({
        'type': 'mark_read',
        'data': {'id': notificationId},
      });

      // 更高效的方式：直接查找并移除
      final messageToRemove = messageList.firstWhereOrNull(
        (item) => item.id == notificationId,
      );

      if (messageToRemove != null) {
        messageList.remove(messageToRemove);
        unreadCount.value = unreadCount.value > 0 ? unreadCount.value - 1 : 0;
        debugPrint('标记通知 $notificationId 为已读');
      } else {
        debugPrint('未找到通知 $notificationId');
      }
    } else {
      debugPrint('WebSocket未连接，无法标记为已读');
    }
  }

  /// 发送文本消息
  void sendMessage(String message) {
    if (_isDisposed) return;

    if (isConnected) {
      try {
        _webSocket!.add(message);
        debugPrint('📤 发送消息: $message');
      } catch (e) {
        debugPrint('❌ 发送消息失败: $e');
        _handleError(e);
      }
    } else {
      debugPrint('❌ WebSocket未连接，无法发送消息');
      // 可以在这里将消息加入队列，等待重连后发送
    }
  }

  /// 发送JSON格式消息
  void sendJsonMessage(Map<String, dynamic> data) {
    final jsonString = json.encode(data);
    sendMessage(jsonString);
  }

  /// 启动心跳机制
  void _startHeartbeat() {
    _heartbeatTimer?.cancel();
    _heartbeatTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
      if (_isDisposed) {
        timer.cancel();
        return;
      }

      if (isConnected) {
        // 检查最后收到消息的时间，如果超过一定时间没有收到消息，认为连接可能有问题
        final now = DateTime.now().millisecondsSinceEpoch;
        if (now - _lastMessageTimestamp > 60000) {
          // 60秒没有收到任何消息
          debugPrint('⚠️  长时间未收到消息，连接可能已失效');
          _handleDisconnection();
          return;
        }

        sendJsonMessage({
          'type': 'ping',
          'timestamp': now,
        });
        debugPrint('💓 发送心跳包');
      } else {
        // 如果连接已断开，停止心跳
        timer.cancel();
      }
    });
  }

  /// 处理应用回到前台
  void _handleAppResumed() {
    if (_isDisposed) return;

    debugPrint('📱 应用回到前台，检查WebSocket连接状态');
    if (!isConnected && _url != null && !_isConnecting) {
      debugPrint('🔄 尝试重新连接WebSocket');
      _performConnect();
    }
  }

  /// 处理应用进入后台
  void _handleAppPaused() {
    debugPrint('📱 应用进入后台');
    // 可以暂停心跳或降低频率以节省电量
    _heartbeatTimer?.cancel();
  }

  /// 处理连接错误
  void _handleError(dynamic error) {
    if (_isDisposed) return;

    debugPrint('❌ WebSocket错误处理: $error');
    _cleanupConnection();
    _safeAddConnectionState(false);
    _attemptReconnect();
  }

  /// 处理连接断开
  void _handleDisconnection() {
    if (_isDisposed) return;

    debugPrint('🔌 WebSocket连接断开处理');
    _cleanupConnection();
    _safeAddConnectionState(false);
    _attemptReconnect();
  }

  /// 尝试重新连接
  void _attemptReconnect() {
    if (_isDisposed) return;

    if (_reconnectAttempts < _maxReconnectAttempts && _url != null) {
      _reconnectAttempts++;
      final delay = Duration(seconds: _calculateReconnectDelay());

      debugPrint(
          '⏰ 计划在 ${delay.inSeconds} 秒后重连 ($_reconnectAttempts/$_maxReconnectAttempts)');

      _reconnectTimer = Timer(delay, () {
        if (!_isDisposed && !isConnected && !_isConnecting) {
          _performConnect();
        }
      });
    } else {
      debugPrint('🛑 达到最大重连次数 ($_maxReconnectAttempts)，停止自动重连');
    }
  }

  /// 计算重连延迟 - 指数退避算法
  int _calculateReconnectDelay() {
    return _reconnectAttempts * 2; // 2, 4, 6, 8, 10秒
  }

  /// 清理连接相关资源
  void _cleanupConnection() {
    _heartbeatTimer?.cancel();
    _heartbeatTimer = null;

    _reconnectTimer?.cancel();
    _reconnectTimer = null;

    _isConnecting = false;

    if (_webSocket != null) {
      try {
        _webSocket!.close();
      } catch (e) {
        debugPrint('❌ 关闭WebSocket连接失败: $e');
      }
      _webSocket = null;
    }
  }

  /// 清理所有资源
  void _cleanupResources() {
    debugPrint('🧹 清理WebSocket资源');
    _cleanupConnection();

    if (!_messageController.isClosed) {
      _messageController.close();
    }

    if (!_connectionController.isClosed) {
      _connectionController.close();
    }
  }

  /// 安全断开连接
  void _safeDisconnect() {
    if (_isDisposed) return;
    disconnect();
  }

  /// 主动断开连接
  void disconnect() {
    debugPrint('👋 主动断开WebSocket连接');
    _reconnectAttempts = _maxReconnectAttempts; // 防止自动重连
    _cleanupResources();
  }

  /// 获取连接状态信息（用于调试）
  Map<String, dynamic> getConnectionInfo() {
    return {
      'isConnected': isConnected,
      'isConnecting': _isConnecting,
      'isDisposed': _isDisposed,
      'url': _url,
      'reconnectAttempts': _reconnectAttempts,
      'maxReconnectAttempts': _maxReconnectAttempts,
      'unreadCount': unreadCount.value,
      'messageCount': messageList.length,
      'lastMessageTimestamp': _lastMessageTimestamp,
    };
  }

  /// 强制重连（用于手动恢复连接）
  Future<void> forceReconnect() async {
    if (_isDisposed) return;

    debugPrint('🔄 强制重连WebSocket');
    _reconnectAttempts = 0;
    _cleanupConnection();
    await _performConnect();
  }
}
